<template>
  <a-layout>
    <a-layout-content
      :style="{
        background: '#fff',
        padding: '24px',
        margin: 0,
        minHeight: '280px',
      }"
    >
      <!-- 使用栅格系统  默认设置24分 -->
      <a-row :gutter="24">
        <!-- 左边table占据8份 -->
        <a-col :span="8">
          <p>
            <a-button type="primary" @click="add()" size="lage">
              新增
            </a-button>
          </p>
          <!-- 表格 -->
          <a-table
            :columns="columns"
            :row-key="(record) => record.id"
            :data-source="level1"
            :pagination="false"
            :loading="loading"
            :defaultExpandAll="true"
          >
            <template #cover="{ text: cover }">
              <img
                v-if="cover"
                :src="cover"
                alt="avatar"
                style="width: 20%; height: 20%"
              />
            </template>
            <template v-slot:action="{ text, record }">
              <a-space size="small">
                <a-button type="primary" @click="edit(record)"> 编辑 </a-button>
                <a-popconfirm
                  title="删除后不可恢复，是否删除"
                  ok-text="是"
                  cancel-text="否"
                  @confirm="handleDelete(record.id)"
                >
                  <a-button type="primary" danger> 删除 </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table>
        </a-col>
        <!-- 右边form占据16份 -->
        <a-col :span="16">
          <!-- 保存按钮 -->
          <p style="margin-left: 300px">
            <a-button type="primary" @click="handleSave()"> 保存 </a-button>
          </p>
          <!-- 表单 -->
          <a-form
            :model="doc"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 18 }"
          >
            <a-form-item label="名称">
              <a-input v-model:value="doc.name" />
            </a-form-item>
            <a-form-item label="父文档">
              <a-tree-select
                v-model:value="doc.parent"
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="treeSelectData"
                placeholder="请选择父文档"
                tree-default-expand-all
                :field-names="{
                  children: 'children',
                  label: 'name',
                  value: 'id',
                }"
              >
              </a-tree-select>
            </a-form-item>
            <a-form-item label="顺序">
              <a-input v-model:value="doc.sort" />
            </a-form-item>
            <!-- 提供一个预览按钮 -->
            <a-form-item label="内容预览">
              <a-button type="primary" @click="handlePreviewContent()">
                <EyeOutlined /> 内容预览
              </a-button>
            </a-form-item>
            <!-- 富文本的div -->
            <a-form-item label="内容">
              <div id="content"></div>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>

      <!-- 提供一个抽屉组件-用于预览展示文档content信息 -->
      <a-drawer
        width="900"
        placement="right"
        :closable="false"
        :visible="drawerVisible"
        @close="onDrawerClose"
      >
        <div class="wangeditor" :innerHTML="previewHtml"></div>
      </a-drawer>
    </a-layout-content>
  </a-layout>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref, createVNode } from "vue";
import axios from "axios";
import { message, UploadProps, Modal } from "ant-design-vue";
import { Tool } from "@/utils/tool";
// 导入路由组件
import { useRoute } from "vue-router";

// 导入ant-design的icons
import ExclamationCircleOutlined from "@ant-design/icons-vue/ExclamationCircleOutlined";

//导入wangeditor
import E from "wangeditor";

export default defineComponent({
  name: "Admindoc",
  components: {
    // UploadOutlined
  },
  setup() {
    //获取路由对象及信息
    const route = useRoute();
    console.log("路由：", route);
    console.log("route.query：", route.query);
    //定义一个数组常量来存储树形控件的data数据
    const treeSelectData = ref();
    treeSelectData.value = [];
    //一个数组存放id集合【提交的值】、一个数组存放文档的name集合【提示】
    const deleteIds: Array<string> = [];
    const deleteNames: Array<string> = [];

    // 定义一个方法来获取当前及子节点的函数
    const getDeleteIds = (treeSelectData: any, id: any) => {
      // 遍历数组，即遍历某一层节点
      for (let i = 0; i < treeSelectData.length; i++) {
        const node = treeSelectData[i];
        if (node.id === id) {
          // 如果当前节点就是目标节点
          console.log("deleteIds", node);
          // 赋值到ids和names
          deleteIds.push(id);
          deleteNames.push(node.name);
          // 遍历所有子节点，将所有子节点全部都加上disabled
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            for (let j = 0; j < children.length; j++) {
              getDeleteIds(children, children[j].id);
            }
          }
        } else {
          // 如果当前节点不是目标节点，则到其子节点再找找看。
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            getDeleteIds(children, id);
          }
        }
      }
    };
    //
    const docs = ref();
    const pagination = ref({
      current: 1,
      pageSize: 3,
      total: 0,
    });
    const loading = ref(false);

    //字段列表
    const columns = [
      {
        title: "名称",
        dataIndex: "name",
      },
      {
        title: "Action",
        key: "action",
        slots: { customRender: "action" },
      },
    ];
    // ----------------富文本预览--------------
    const drawerVisible = ref(false); //抽屉可视化的变量
    const previewHtml = ref(); //存放html内容content
    //定义方法来进行赋值content信息到previewHtml
    const handlePreviewContent = () => {
      //获取html内容
      const html = editor.txt.html();
      //赋值给previewHtml
      previewHtml.value = html;
      //设置标志位为true
      drawerVisible.value = true;
    };
    //抽屉关闭触发的函数
    const onDrawerClose = () => {
      //设置为空
      previewHtml.value = {};
      //设置标志位为false
      drawerVisible.value = false;
    };
    // -------- 表单 ---------

    // const docIds = ref();
    const doc = ref();
    //先初始化value、ebookId
    doc.value = {
      ebookId: route.query.ebookId,
    };

    //创建editor对象、绑定某个div块
    const editor = new E("#content");
    //设置zIndex[放置底层]
    editor.config.zIndex = 0;
    // 显示上传图片按钮，转成Base64存储，同时也支持拖拽图片
    editor.config.uploadImgShowBase64 = true;

    const modalVisible = ref(false);
    const modalLoading = ref(false);

    //保存-修改-新增操作
    const handleSave = () => {
      //获取富文本的数据
      doc.value.content = editor.txt.html();
      // console.log( doc.value.content);
      //发起请求
      axios.post("/doc/save", doc.value).then((resp) => {
        const data = resp.data;
        if (data.success) {
          //提示
          message.success("内容保存成功！！");
          //重新加载列表
          handleQuery();
        } else {
          //提示
          message.error("操作有误，请稍后尝试！！");
        }
      });
    };

    //添加
    const add = () => {
      //清空富文本数据
      editor.txt.html("");
      doc.value = {};
      //设置新增的ebookid
      doc.value = {
        ebookId: route.query.ebookId,
      };
      //给treeSelectData赋值
      treeSelectData.value = Tool.copy(level1.value) || [];
      //在treeSelectData中添加无父节点的选项【parent=0】
      treeSelectData.value.unshift({ id: 0, name: "无" });
    };

    //编辑【修改设置当前及旗下子节点禁用】
    const edit = (record: any) => {
      //将数据赋值给form绑定的对象数据
      doc.value = Tool.copy(record);
      //查询content的内容
      axios.get("/doc/find-content/" + record.id).then((resp) => {
        const data = resp.data;
        //清空富文本中的内容
        editor.txt.html("");
        editor.txt.html(data.content);
      });
      //对话框显示
      modalVisible.value = true;
      //禁止当前及子节点选择
      setDisable(treeSelectData.value, record.id);
    };

    /**
     * 删除数据
     */
    const handleDelete = (id: number) => {
      //每次操作前先清空数组
      deleteIds.length = 0;
      deleteNames.length = 0;
      // console.log("before===>"+deleteIds.join(","));
      //调用递归算法函数赋值deleteIds和deleteNames
      getDeleteIds(level1.value, id);
      console.log(deleteIds.join(","));
      //发起请求delete
      axios.delete("/doc/delete/" + deleteIds.join(",")).then((resp) => {
        console.log(resp);
        if (resp.data.success) {
          handleQuery();
        } else {
          message.error("删除操作失败！！");
        }
      });
    };

    //编写一个方法将选项禁止掉【当前及子选项disabled】
    const setDisable = (treeSelectData: any, id: any) => {
      //遍历数组treeSelectData、判断是否为当前节点或字节【递归】
      for (let i = 0; i < treeSelectData.length; i++) {
        //把当前遍历到的节点获取出来，然后进行判断
        const node = treeSelectData[i];
        //判断为当前的目标节点
        if (node.id == id) {
          //为当前的目标节点
          node.disabled = true;
          //还要遍历子节点【判断有没有子节点】
          const children = node.children;
          //判断children是否为空
          if (Tool.isNotEmpty(children)) {
            //不为空，再迭代一次
            for (let j = 0; j < children.length; j++) {
              setDisable(children, children[j].id);
            }
          }
        } else {
          //不为目前节点
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            //不为空，再迭代一次
            setDisable(children, id);
          }
        }
      }
      //
    };

    /*
     * 数据查询
     * */
    const level1 = ref();
    const handleQuery = () => {
      loading.value = true;
      axios
        .get("/doc/all", {
          params: {
            ebookId: route.query.ebookId,
          },
        })
        .then((resp) => {
          loading.value = false;
          const data = resp.data;

          if (data.success) {
            console.log("原始数据：", data.content);

            level1.value = [];
            level1.value = Tool.array2Tree(data.content, 0);
            console.log("树形结构：", level1);

            //给treeSelectData赋值
            treeSelectData.value = Tool.copy(level1.value) || [];
            //在treeSelectData中添加无父节点的选项【parent=0】
            treeSelectData.value.unshift({ id: 0, name: "无" });
          } else {
            message.error(data.message);
          }
        });
    };

    onMounted(() => {
      handleQuery();

      //定时器
      setTimeout(() => {
        editor.create();
      }, 100);
    });
    return {
      docs,
      pagination,
      columns,
      loading,

      edit,
      doc,
      modalVisible,
      modalLoading,
      handleSave,

      level1,
      treeSelectData,
      add,
      handleDelete,

      drawerVisible,
      previewHtml,
      handlePreviewContent,
      onDrawerClose,
    };
  },
});
</script>

<style scoped>
/* tile uploaded pictures */
.upload-list-inline :deep(.ant-upload-list-item) {
  float: left;
  width: 200px;
  margin-right: 8px;
}
.upload-list-inline [class*="-upload-list-rtl"] :deep(.ant-upload-list-item) {
  float: right;
}
</style>
